package com.study.spmongodb.wwj.juc.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author MI
 * @version 1.0
 * @date 2020/12/13 17:27
 */
public class ReadWriteLockExample {
    private final static ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);

    private final static ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
    private final static ReentrantReadWriteLock.ReadLock readLock = lock.readLock();


    private final static List<Long> data = new ArrayList<>();

    public static void main(String[] args) throws InterruptedException {

        new Thread(() -> {
            write();
        }).start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(() -> read()).start();
        new Thread(() -> read()).start();

    }

    public static void write() {
        writeLock.lock();
        try {
            data.add(System.currentTimeMillis());
            TimeUnit.SECONDS.sleep(5);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }

    public static void read() {
        readLock.lock();
        try {
            data.forEach(System.out::println);
            TimeUnit.SECONDS.sleep(5);
            System.out.println(Thread.currentThread().getName() + "======================");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
    }
}
